package com.cdtu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtu.entity.Modules;
import com.cdtu.service.ModulesService;
import com.cdtu.mapper.ModulesMapper;
import com.cdtu.vo.AdminModulesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 玉总
* @description 针对表【modules】的数据库操作Service实现
* @createDate 2023-01-12 19:44:27
*/
@Service
public class ModulesServiceImpl extends ServiceImpl<ModulesMapper, Modules>
    implements ModulesService{
 @Autowired
 ModulesMapper modulesMapper;

 @Override
 public List<AdminModulesVo> getModules(long id) {
  List<Modules> modules = modulesMapper.getModules(id);
  List<AdminModulesVo> modulesVos=new ArrayList<>();
  for (Modules module : modules) {
       if (module.getParentId() == null){
        List<Modules> child= new ArrayList<>();
        //一级模块
        AdminModulesVo adminModulesVo = new AdminModulesVo();
        BeanUtil.copyProperties(module,adminModulesVo);
        //二级模块
        for (Modules module1 : modules) {
             if (module.getId() == module1.getParentId()){
                 child.add(module1);
             }
        }
        adminModulesVo.setChild(child);
       modulesVos.add(adminModulesVo);
       }
  }
  return modulesVos;
 }

    @Override
    public List<Long> getByIdSecondaryPermission(long id) {
        List<Modules> modules = modulesMapper.getModules(id);
        List<Long> permissions=new ArrayList<>();
        //获取二级权限
        for (Modules module : modules) {
            if (module.getParentId()!=null){
                permissions.add(module.getId());
            }
        }
        return permissions;
    }

    @Override
    public Boolean updatePermission(long id, String ids) {
      // 1.先删除原有的权限模块
        modulesMapper.byIdDeleteModulePermisson(id);
      // 2.在插入型的模块
       if(!StrUtil.isBlank(ids)){
           String[] split = ids.split(",");
           for (String moduleId : split) {
               modulesMapper.byIdInsertModulePermisson(id, Long.parseLong(moduleId));
           }
       }
        return true;
    }
}




